from django.shortcuts import render, HttpResponse
from .models import User, Article, Category, UserExtension, Tag


def index(request):
    # TODO: 新增数据
    # category = Category(name='最新文章')
    # category.save()
    #
    # user = User(username='知了')
    # user.save()
    #
    # article = Article(title='钢铁是怎样炼成的？', content='123456abc')
    # article.category = category
    # article.user = user
    # article.save()

    category = Category.objects.first()
    # user = User.objects.first()
    user = User.objects.get(pk=2)
    # article = Article(title='百年孤独', content='12456abc')
    # article.category = category
    # article.user = user
    # article.save()

    # TODO: 获取数据
    # TODO: 获取文章分类下的所有文章
    # articles = category.articles.all()

    # TODO: 获取作者名下所有文章
    # articles = user.articles.all()
    # print(articles)
    # for article in articles:
    #     print(article)

    # TODO: 通过文章分类直接插入数据
    article = Article(title='唐诗三百首', content='唐诗三百首')
    article.user = user
    # TODO: 自动保存数据
    category.articles.add(article, bulk=False)
    return HttpResponse('success')


def one_to_one_view(request):
    # TODO: 新增数据
    user = User.objects.get(pk=1)
    # userextenions = UserExtension(school='浙江大学')
    # userextenions.user = user
    # userextenions.save()

    # TODO: 查询数据
    print(user.extension)

    userextenions = UserExtension.objects.first()
    print(userextenions.user)
    return HttpResponse('success')


def many_to_many_view(request):
    # TODO: 添加数据
    # user = User.objects.first()
    # category = Category.objects.first()
    # article = Article(title='倚天屠龙记', content='倚天屠龙记')
    # article.user = user
    # article.category = category
    # article.save()

    # article = Article.objects.get(pk=7)
    # tag = Tag(name='最热收录')
    # tag.save()
    # tag.articles.add(article)

    # tag = Tag.objects.get(pk=2)
    # artilce = Article.objects.get(pk=6)
    # tag.articles.add(artilce)

    # TODO: 查询数据
    # TODO: 根据tag标签查询文章
    # tag = Tag.objects.get(pk=2)
    # articles = tag.articles.all()
    # for article in articles:
    #     print(article)
    #     print('*' * 30)

    # TODO: 根据文章查询tag标签
    article = Article.objects.get(pk=7)
    tags = article.tag.all()
    for tag in tags:
        print(tag)

    return HttpResponse('success')
